from django.shortcuts import render
from django.http import HttpResponse
from common.models import Users
from django.db.models import Q
from datetime import datetime

import time
import os
from PIL import Image
from django.core.paginator import Paginator

'''==============后台会员信息管理======================'''


def index(request, pIndex):
    '''浏览会员信息'''
    list = Users.objects.all()
    # 获取会员信息查询对象
    mod = Users.objects
    mywhere = []  # 定义一个用于存放搜索条件列表
    # 获取、判断并封装关keyword键搜索
    kw = request.GET.get("keyword", None)
    if kw:
        # 查询会员账号名中只要含有关键字的都可以
        list = mod.filter(username__contains=kw)  # 关键字查询的语法格式
        mywhere.append("keyword=" + kw)
    else:
        list = mod.filter()
    # 获取、判断并封装会员性别sex搜索条件
    sex = request.GET.get('sex', '')
    if sex != '':
        list = list.filter(sex=sex)
        mywhere.append("sex=" + sex)
    # 分页显示
    p = Paginator(list, 4)
    maxpage = p.num_pages  # 最大页数
    if pIndex == '' or int(pIndex) < 1:
        pIndex = "1"
    if int(pIndex) > maxpage:
        pIndex = maxpage
    list2 = p.page(pIndex)  # 取当前页的信息
    plist = p.page_range  # 取页码总数
    context = {'userslist': list2, 'plist': plist, 'pIndex': int(pIndex), 'sex': sex,'mywhere': mywhere}  # 将信息封装到字典中
    return render(request, 'myadmin/users/index.html', context)


def add(request):
    '''加载添加页面'''
    return render(request, 'myadmin/users/add.html')


def insert(request):
    '''执行信息添加'''
    try:
        # 实例化Users类对象并取得值
        ob = Users()
        ob.username = request.POST['username']
        ob.name = request.POST['name']
        # 获取密码并md5
        import hashlib
        m = hashlib.md5()
        m.update(bytes(request.POST['password'], encoding="utf8"))
        ob.password = m.hexdigest()
        ob.sex = request.POST['sex']
        ob.address = request.POST['address']
        ob.code = request.POST['code']
        ob.phone = request.POST['phone']
        ob.email = request.POST['email']
        ob.state = 1
        ob.addtime = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
        ob.save()
        context = {'info': '添加成功！'}
    except Exception as err:
        print(err)
        context = {'info': '添加失败！'}
    return render(request, "myadmin/info.html", context)


def delete(request, uid):
    '''删除信息'''
    try:
        ob = Users.objects.get(id=uid)
        ob.delete()
        context = {'info': '删除成功！'}
    except:
        context = {'info': '删除失败！'}
    return render(request, "myadmin/info.html", context)


def edit(request, uid):
    '''加载编辑信息页面'''
    try:
        ob = Users.objects.get(id=uid)
        context = {'user': ob}
        return render(request, "myadmin/users/edit.html", context)
    except Exception as err:
        context = {'info': '没有找到要修改的信息！'}
        return render(request, "myadmin/info.html", context)


def update(request, uid):
    '''执行会员信息编辑'''
    try:
        ob = Users.objects.get(id=uid)
        ob.state = request.POST['state']
        ob.save()
        context = {'info': '修改成功！'}
    except Exception as err:
        context = {'info': '修改失败！'}
    return render(request, "myadmin/info.html", context)


def repassword(request, uid):
    '''加载重置密码页面'''
    ob = Users.objects.get(id=uid)
    context = {'user': ob}
    return render(request, 'myadmin/users/repassword.html', context)


def reset(request, uid):
    '''执行密码重置'''
    try:
        ob = Users.objects.get(id=uid)
        # 获取密码并md5
        import hashlib
        m = hashlib.md5()
        m.update(bytes(request.POST['password'], encoding="utf8"))
        ob.password = m.hexdigest()
        ob.save()
        context = {'info': '修改成功！'}
    except Exception as err:
        context = {'info': '修改失败！'}
    return render(request, "myadmin/info.html", context)
